package cn.edu.zxj.aptcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-03-19
 * @time: 15:05:07
 */
@RequestMapping("/admin")
@RestController
public class CaptchaController {

    private static final String ADMIN_KAPTCHA_SESSION_KET = "ADMIN_KAPTCHA_SESSION_KET";
    private static final String ADMIN_KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";

    private static final Long SESSION_TIMEOUT = 60 * 1000L;


    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session) {
        // 1. 验证参数是否正确
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        // 2. 获取 session
        String saveCaptcha = (String) session.getAttribute(ADMIN_KAPTCHA_SESSION_KET);
        Date saveDate = (Date) session.getAttribute(ADMIN_KAPTCHA_SESSION_DATE);

        // 3. 对于验证码
        if (captcha.equals(saveCaptcha)) {
            // 4. 对于时间
            if (saveDate == null){
                return false;
            }
            long time = System.currentTimeMillis() - saveDate.getTime();
            return time <= SESSION_TIMEOUT;
        }

        return false;
    }
}
